Shell脚本实战02-批量改名

1. 将下面的这些文件中的theshu字符串全部改成wang(最好用for循环实现),并且将扩展名html全部改成大写。

1
2
3
4
5
6
7
8
9
10
11
[root@theshu shell]# ll /root
-rw-r--r-- 1 root root 0 3月 5 10:42 apjgfskqhf_theshu.html
-rw-r--r-- 1 root root 0 3月 5 10:42 bwrzszktlg_theshu.html
-rw-r--r-- 1 root root 0 3月 5 10:42 dmtmguxncz_theshu.html
-rw-r--r-- 1 root root 0 3月 5 10:42 dnsxbazfqa_theshu.html
-rw-r--r-- 1 root root 0 3月 5 10:42 ecjeopdntb_theshu.html
-rw-r--r-- 1 root root 0 3月 5 10:42 glpvylszpu_theshu.html
-rw-r--r-- 1 root root 0 3月 5 10:42 otyiatwrnd_theshu.html
-rw-r--r-- 1 root root 0 3月 5 10:42 qbdxjmntlg_theshu.html
-rw-r--r-- 1 root root 0 3月 5 10:42 udgufgakwk_theshu.html
-rw-r--r-- 1 root root 0 3月 5 10:42 urdcucyxxu_theshu.html

1.1. 问题分析

知识点是对文件进行批量改名。

1.2. 参考答案1

1
2
3
4
5
6
7
8
9
#!/bin/bash
Filename=_wang.HTML
Dirname="/root"
cd $Dirname || exit 1
for n in `ls`
do
name=$(echo ${n} | awk -F '_' '{print $1}')
mv $n ${name}${Filename}
done

1.3. 参考答案2(非循环实现方法)

1
2
3
4
#!/bin/bash
Path="/root"
cd $Path && \
ls | awk -F '_' '{print "mv "$0" "$1"_wang.HTML"}' | bash

1.4. 参考答案3:专业的事情交给专业的人做

1
# rename theshu.html wang.HTML *.html

1.5. 执行结果

1
2
3
4
5
6
7
8
9
10
11
[root@AmingLinux-107 shell]# ll /root
-rw-r--r-- 1 root root 0 3月 5 10:42 apjgfskqhf_wang.HTML
-rw-r--r-- 1 root root 0 3月 5 10:42 bwrzszktlg_wang.HTML
-rw-r--r-- 1 root root 0 3月 5 10:42 dmtmguxncz_wang.HTML
-rw-r--r-- 1 root root 0 3月 5 10:42 dnsxbazfqa_wang.HTML
-rw-r--r-- 1 root root 0 3月 5 10:42 ecjeopdntb_wang.HTML
-rw-r--r-- 1 root root 0 3月 5 10:42 glpvylszpu_wang.HTML
-rw-r--r-- 1 root root 0 3月 5 10:42 otyiatwrnd_wang.HTML
-rw-r--r-- 1 root root 0 3月 5 10:42 qbdxjmntlg_wang.HTML
-rw-r--r-- 1 root root 0 3月 5 10:42 udgufgakwk_wang.HTML
-rw-r--r-- 1 root root 0 3月 5 10:42 urdcucyxxu_wang.HTML
0%